package com.wangjie.order.service.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.wangjie.order.entity.Order;
import com.wangjie.order.feign.ProductFeignClient;
import com.wangjie.order.service.OrderService;
import com.wangjie.product.entity.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private RestTemplate restTemplate;

    @SentinelResource(value = "createOrder", blockHandler = "createOrderFallback")
    @Override
    public Order createOrder(Long userId, Long productId) {
        // Product product = getProductFromRemote(productId);
        // Product product = getProductFromRemoteWithLoadBalance(productId);
        // Product product = getProductFromRemoteWithLoadBalanceAnnotation(productId);
        Product product = productFeignClient.getProduct(productId);
        Order order = new Order();
        order.setId(1L);
        order.setTotalAmount(product.getPrice().multiply(new BigDecimal(product.getNum())));
        order.setUserId(userId);
        order.setNickName("miranda");
        order.setAddress("陕西西安");
        order.setProductList(Arrays.asList(product));
        return order;
    }

    // 兜底回调
    public Order createOrderFallback(Long userId, Long productId, BlockException e) {
        Order order = new Order();
        order.setId(0L);
        order.setTotalAmount(new BigDecimal("0"));
        order.setUserId(userId);
        order.setNickName("未知用户");
        order.setAddress("异常信息: " + e.getClass());
        return order;
    }

    private Product getProductFromRemote(Long productId) {
        // 获取商品服务所有机器的 ip + port
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        ServiceInstance instance = instances.get(0);
        // 远程 url
        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/product/" + productId;
        log.info("远程请求url: {}", url);
        // 发送请求
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }

    // 负载均衡发送请求
    private Product getProductFromRemoteWithLoadBalance(Long productId) {
        ServiceInstance instance = loadBalancerClient.choose("service-product");
        // 远程 url
        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/product/" + productId;
        log.info("远程请求url: {}", url);
        // 发送请求
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }

    // 基于注解的负载均衡
    private Product getProductFromRemoteWithLoadBalanceAnnotation(Long productId) {
        // 远程 url
        String url = "http://service-product/product/" + productId;
        log.info("远程请求url: {}", url);
        // 发送请求
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }
}
